package com.example.sourcecodelearning.unsafe;

import lombok.SneakyThrows;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeUtils {

    @SneakyThrows
    public static Unsafe getUnsafe() {
        // Unsafe unsafe = Unsafe.getUnsafe()这样会报错，需要反射获取
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        // 将`theUnsafe`标记为可访问，这样即使`theUnsafe`是私有字段，也可以通过反射获取它。
        theUnsafe.setAccessible(true);
        // 通过`theUnsafe`对象获取`Unsafe`类的实例。这里的`null`参数表示`theUnsafe`字段是`Unsafe`类的一个静态字段
        return (Unsafe) theUnsafe.get(null);
    }
}
